class Item < ActiveRecord::Base
 belongs_to :feed
 has_and_belongs_to_many :categories
 before_save :close_tags
 
 # this method closes any unclosed tags. It is courtesy of http://www.bigbold.com/snippets/posts/show/295
 def close_tags
  if self.description
    h1 = {}
    h2 = {}
    self.description.scan(/\<([^\>\s\/]+)[^\>\/]*?\>/).each { |t| h1[t[0]] ? h1[t[0]] += 1 : h1[t[0]] = 1 }
    self.description.scan(/\<\/([^\>\s\/]+)[^\>]*?\>/).each { |t| h2[t[0]] ? h2[t[0]] += 1 : h2[t[0]] = 1 }
    h1.each {|k,v| self.description += "</#{k}>" * (h1[k] - h2[k].to_i) if h2[k].to_i < v }
  end
 end
 
 def Item.date_count(date=Time.now.at_midnight)
   Item.find(:all, :conditions=>"pubDate<='#{date.tomorrow.to_s(:db)}' and pubDate>='#{date.to_s(:db)}'").length rescue 0 
 end
 
 def Item.month_count(year,month)
    Item.find(:all, :conditions=>["month(pubDate)=? and year(pubDate)=?",month,year]).length rescue 0
 end

 def Item.time_of_day_count(hour)
   Item.find(:all, :conditions=>"HOUR(TIME(pubDate))='#{hour}'").length rescue 0
 end

 def Item.day_of_week_count(day)
   Item.find(:all, :conditions=>["dayofweek(pubDate)=?",day]).length rescue nil
 end

 def Item.authority_count(authority_id)
   Item.find_by_sql(["select items.* from items, feeds where items.feed_id=feeds.id and feeds.authority_id=?",authority_id]).length rescue 0
 end
 
end
